## 二维平面的运算公式
from math import  sqrt,sin,cos,atan2
from ExternalTools.vector_drawing import *

# 恐龙图像 
dino_vectors = [(6,4),(3,1),(1,2),(-1,5),(-2,5),(-3,4),(-4,4),(-5,3),(-5,2),(-2,2),(-5,1),(-4,0),(-2,1),(-1,0),(0,-3),(-1,-4),(1,-4),(2,-3),(1,-2),(3,-1),(5,1)];

# 二维加法
def add(v1, v2):
    return (v1[0] + v2[0], v1[1] + v2[1]);

# 二维减法
def subtract(v1, v2):
    return (v1[0] - v2[0], v1[1] - v2[1]);

# 勾股定理(求向量长度)
def length(v):
    return sqrt(v[0]**2 + v[1]**2);

# 二维加法(任意数量)
def adds(*vectors):
    return (sum([v[0] for v in vectors]), sum([v[1] for v in vectors]));

# 二维加法(根据一个向量对一个向量几个进行平移(相加)处理)
def translate(translation, vectors):
    return [add(translation, v) for v in vectors];

# 向量与标量相乘
def scale(scalar, v):
    return (scalar * v[0], scalar * v[1]);

# 两个向量之间的距离(距离就是两个向量之差的长度)
def distance(v1, v2):
    return  length(subtract(v1,v2));

# 根据一组向量，计算周长
def perimeter(vectors):
    distances = [distance(vectors[i], vectors[(i+1)%len(vectors)])
                 for i in range(0, len((vectors)))]
    return  sum(distances)

# 画100个不重叠的小恐龙
def hundred_dinos():
    translations = [(12 * x,10 * y)
                    for x in range(-5,5)
                    for y in range(-5,5)]
    dions = [Polygon(*translate(t, dino_vectors),color=blue)
             for t in translations];
    draw(*dions, grid = None, axes=None, origin=None);

# 接受极坐标(长度, 弧度)返回笛卡尔坐标
def to_cartesian(polar_vector):
    length, angle = polar_vector[0], polar_vector[1]
    return (length * cos(angle), length * sin(angle))

# 接受笛卡尔坐标返回极坐标(长度, 弧度)
def to_polar(vector):
    x, y = vector[0],vector[1]
    angle = atan2(x,y)
    return  (length(vector, angle))

# 接收笛卡尔坐标向量数组和一个角度, 返回旋转后的向量数组
def rotate(angle, vectors):
    polars = [to_polar(v) for v in vectors] # 先转极坐标
    return [to_cartesian((l, a + angle)) for l,a in polars] # 返回时转笛卡尔坐标

# 返回一个规则n边形
def regular_polygon(n):
    return [to_cartesian((1, 2*pi*k/n)) for k in range(0,n)]